<?php

namespace app\index\controller;

use app\model\MemberImage;
use app\service\PlatFormFactory;
use GuzzleHttp\Client;
use think\exception\ValidateException;
use app\model\Member;
use app\model\Users;
use app\model\Agent;
use app\model\Curl;
use app\model\WxBizDataCrypt;
use app\model\Config;
use app\model\CouponReceive;
use app\model\Technical;
use app\model\Wxmini;
use app\model\Openid;
use app\model\OrderStaff;


use EasyWeChat\Factory;
use think\image\Exception;

class MemberController extends Base
{
    public function detail()
	{
		// $this->updatanickname();

        $platform = request()->header('platform');

        /*if ($platform !== PlatFormFactory::H5){
            $Membermob = new Member;
            $memberinfo = $Membermob->getUserByWechat();
        }else{
            $memberinfo = Member::where('id',$this->userInfo['id'])->find();
        }*/
        $memberinfo = Member::where('id',$this->userInfo['id'])->find()->toArray();
        $memberinfo = Member::setmemberinfo($memberinfo);

		$memberinfo['is_agent'] = (int) $memberinfo['is_agent'];

		$user_id = $memberinfo['id'];
		if ($memberinfo['primaryuid']) {
			$user_id = $memberinfo['primaryuid'];
		}

		$user = Users::getuserbyuid($user_id);

		if (!empty($user)) {
			$memberinfo['is_user'] = 1;
		} else {
			$memberinfo['is_user'] = 0;
		}
		if (!empty($user['sid'])) {
			$memberinfo['is_storeadmin'] = 1;
		} else {
			$memberinfo['is_storeadmin'] = 0;
		}

		$Agent = Agent::where(['uniacid' => uniacid(), 'uid' => $user_id])->find();
		if (!empty($Agent)) {
			$memberinfo['agent'] = $Agent->toArray();
		} else {
			$memberinfo['agent']['income'] = 0;
		}

		$Technical = Technical::where(['uniacid' => uniacid(), 'uid' => $user_id])->find();
		if (!empty($Technical)) {
			$Technical = $Technical->toArray();
		}

		if (!empty($Technical)) {
			$memberinfo['is_technical'] = $Technical['status'];
		} else {
			$memberinfo['is_technical'] = 0;
		}

		if ($memberinfo['nickname'] == '微信用户' || $memberinfo['nickname'] == '匿名用户') {
			$memberinfo['nickname'] = "";
		}

		$memberinfo['coupon'] = (int) CouponReceive::where(['uniacid' => uniacid(), 'uid' => $memberinfo['uid']])->count();

		$memberinfo['sex'] = sex($memberinfo['sex']);

		if (input('get.v') == Config::getconfig()['program_version']) {
			$memberinfo['is_audit'] = 1;
		} else {
			$memberinfo['is_audit'] = 0;
		}

		$data = $memberinfo;
        unset($data['pay_pwd']);
		return $this->json(['data' => $data]);
	}

	public function getkefuurl()
	{
		$orderid = input('get.orderid');

		$technicalId = OrderStaff::getuuid($orderid);
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();
		$data['url'] = gethost() . TP_APIURL . '/h5-im?toid=' . Openid::getMpOpenidbyuuid($technicalId) . '&uid=' . $memberinfo['id'] . '&xmtoken=' . $this->getToken();

		return $this->json(['data' => $data]);
	}
	public function getsetmpurl()
	{
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();

		$data['url'] = gethost() . TP_APIURL . '?s=/index/member/setmpopenid&xmtoken=' . $this->getToken() . '&uid=' . $memberinfo['id'];

		return $this->json(['data' => $data]);
	}

	public function setmpopenid()
	{
		$uniacid = uniacid();
		$openid = input('get.openid');

		$backurl = gethost() . $_SERVER["SCRIPT_NAME"] . '?s=/index/member/setmpopenid&xmtoken=' . $this->getToken() . '&uid=' . input('get.uid');
		if (empty($openid)) {
			$url = gethost() . $_SERVER["SCRIPT_NAME"] . '?s=/index/wechatmp/getopenid&xmtoken=' . $this->getToken() . '&uid=' . input('get.uid') . '&backurl=' . urlencode($backurl);
			return redirect($url);
		} else {
			$uid = input('get.uid');
			if (empty(Openid::where(['uniacid' => $uniacid, 'ptype' => 'mp', 'openid' => $openid])->find())) {
				Openid::create([
					'uniacid' => $uniacid,
					'ptype' => 'mp',
					'uid' => $uid,
					'openid' => $openid
				]);
			}
		}
		echo <<< EOT
			<!DOCTYPE html>
			<html lang="zh-cmn-Hans">
			<head>
				<meta charset="UTF-8">
				<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
				<title>绑定公众号信息提醒</title>
				<link rel="stylesheet" href="static/style/weui.css"/>
			</head>
			<body ontouchstart data-weui-mode="care" >
				<div class="weui-msg">
					<div class="weui-msg__icon-area"><i class="weui-icon-success weui-icon_msg"></i></div>
					<div class="weui-msg__text-area">
						<h2 style="text-align: center;" class="weui-msg__title">设置成功</h2>
					</div>
				</div>
			</body>
			</html>
EOT;
	}

	public function openid()
	{
		$code = input('get.code');
        $provider = input('get.provide');
        if ($code) {
            if($provider == 'toutiao'){
                $config = Config::getconfig('miniprogram');

                $client = new Client();
                $response = $client->post( 'https://developer.toutiao.com/api/apps/v2/jscode2session',[
                    'headers'=>[
                        'Content-Type'=>'application/json; charset=utf-8'
                    ],
                    'json'=>[
                        'appid'=> $config['ttapp_id'] , //'ttdd02abbf423eff7201',
                        'secret'=>$config['ttsecret'] ,  //'0280362090a38de62f77cbbd7f33217c7fdbf927',
                        'code'=>$code
                    ]
                ]);

                $data = json_decode($response->getBody()->getContents(),true)['data'];
                $data['ptype'] = 'wxapp';
                $data['sessionid'] = md5(uniqid());
            }else{
                $app = Wxmini::make();
                $data = $app->auth->session($code);
                $data['ptype'] = 'wxapp';
                $data['sessionid'] = md5(uniqid());
            }
        }else{
            $data = $this->userInfo;
        }


		$data['sessionid'] = md5(uniqid());
		$data['uniacid'] = uniacid();

		$this->setToken($data, $data['sessionid']);

		return $this->json(['data' => $data]);
	}
	public function check()
	{
		if ($this->userInfo['openid']) {
			$errno = 0;
		} else {
			$errno = 1;
		}

		return $this->json(['errno' => $errno, 'data' => $this->userInfo]);
	}
	public function userinfo()
	{
		return $this->json(['data' => $this->userInfo]);
	}

	public function getuid()
	{
		$data['uid'] = UID();
		return $this->json(['data' => $data]);
	}

	//获取用户手机号
	public function getsessionkey()
	{
		global $_GPC;

		$code = $_GPC['code'];
		$account = pdo_get('account_wxapp', array('uniacid' => uniacid()));
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $account['key'] . '&secret=' . $account['secret'] . '&js_code=' . $code . '&grant_type=authorization_code';

		$curl = new Curl();
		$curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
		$curl->get($url);
		$result = json_decode($curl->response, true);
		return $this->json(['data' => $result]);
	}

	public function updatanickname()
	{
		$postdata['nickname'] = input('post.nickName');
		$postdata['userpic'] = input('post.avatarUrl');

		if(empty($postdata['nickname'])){
			$postdata['nickname'] =  $this->userInfo['nickname'];
		}

		if(empty($postdata['userpic'])){
			$postdata['userpic'] =  $this->userInfo['avatar'];
		}

		if (!empty($postdata['nickname'])) {
			Member::where('id', UID())->update($postdata);
		}
	}

	public function bindmobile()
	{
		global $_GPC, $_W;

		$uid           = UID();
		$encryptedData = $_GPC['encryptedData'];
		$iv            = $_GPC['iv'];
		$sessionKey    = $_GPC['session_key'];
		$appid = $_W['account']['key'];

		$pc = new WxBizDataCrypt($appid, $sessionKey);
		$errCode = $pc->decryptData($encryptedData, $iv, $data);
		if ($errCode == 0) {
			$phone = json_decode($data, 'true');

			Member::update(['id' => UID(), 'telephone' => $phone['phoneNumber']]);

			return $this->json(['data' => $phone]);
		} else {
			return $this->json(['errno' => 1, 'data' => ['errcode' => $errCode, 'appid' => $appid]]);
		}
	}

	public function bindpid()
	{
		$pid = input('post.pid');

		if (empty($pid)) {
			$pid = input('get.pid');
		}

		if (!empty($pid) && !empty(UID())) {
			$Membermob = new Member;
			$memberinfo = $Membermob->getUserByWechat();

			if (empty($memberinfo['pid'])) {
				if ($memberinfo['id'] != $pid) {
					Member::where('id', UID())->update(['pid' => $pid]);
				}
			}
		}
		return $this->json(['data' => $memberinfo]);
	}

	public function team()
	{
		$data['first'] = Member::field('id,nickname,regdate,userpic')
			->where(['uniacid' => uniacid(), 'pid' => UID()])
			->select()
			->toArray();

		if (!empty($data['first'])) {
			foreach ($data['first'] as &$vo) {
				$vo['regdate'] = time_format($vo['regdate']);

				if (empty($pid)) {
					$pid = $vo['id'];
				} else {
					$pid = $pid . ',' . $vo['id'];
				}
			}
			$pidin = explode(',', $pid);

			$data['second'] = Member::field('id,nickname,regdate,userpic')
				->where(['uniacid' => uniacid(), 'pid' => $pidin])
				->select()
				->toArray();

			foreach ($data['second'] as &$vo) {
				$vo['regdate'] = time_format($vo['regdate']);
			}
		}

		return $this->json(['data' => $data]);
	}

	public function agent()
	{
		$user = Users::getuserbyuid(PUID());
		$data = Agent::field('id,uid,name,tel')
			->where(['uniacid' => uniacid(), 'uid' => $user['id']])
			->select()
			->toArray();

		return $this->json(['data' => $data]);
	}

	public function update()
	{
		$uid = UID();
		$postdata = input('post.');

		if (!empty($postdata['userpic'])) {
			$data['userpic'] = $postdata['userpic'];
		}

		if (!empty($postdata['nickname'])) {
			$data['nickname'] = $postdata['nickname'];
		}

		if (!empty($postdata['sex'])) {

			if ($postdata['sex'] == '男') {
				$data['sex'] = 1;
			} elseif ($postdata['sex'] == '女') {
				$data['sex'] = 2;
			} else {
				$data['sex'] = 0;
			}
		}

		if(!empty($postdata['pay_pwd'])) {
		    $data['pay_pwd'] = $postdata['pay_pwd'];
		    $data['has_pay_pwd'] = 1;
        }
		$data['id'] = $uid;

		Member::update($data);
		return $this->json(['data' => $data]);
	}
	public function login()
	{
		$Configdata = Config::getconfig('common');
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();
		if ($Configdata['WECHAT_REGISTER_CLOSE'] == 1 && input('get.v') != Config::getconfig()['program_version']) {


			if (!empty($memberinfo['name'])) {
				if (empty($memberinfo['status'])) {
					$data['errno'] = 20001;
					return $this->json(['msg' => '账号审核中', 'data' => $data]);
				}
			} else {
				$data['errno']  = 10001;
				return $this->json(['msg' => '您没还完成注册', 'data' => $data]);
			}
		}
		$data['uid'] = $memberinfo['id'];
		$data['errno'] = 0;
		return $this->json(['data' => $data]);
	}

    public function checkPayPwd(){
        $uid = UID();
        $payPwd = input('post.pay_pwd');
        if(empty($payPwd)){
            return $this->json(['errno'=>-1,'message'=>'请输入支付密码']);
        }

        $memberinfo = Member::find($uid);
        if(empty($memberinfo)){
            return $this->json(['errno'=>-1,'message'=>'用户不存在']);
        }

        if($memberinfo->pay_pwd != $payPwd){
            return $this->json(['errno'=>-1,'message'=>'支付密码错误']);
        }

        return $this->json(['errno'=>0]);
    }

    public function applyVip(){
        $uid = UID();
        if(empty($uid)){
            return  $this->json(['errno'=>-1,'message'=>'系统错误']);
        }

        $xingming = input('post.xingming');
        if(empty($xingming)){
            return $this->json(['errno'=>-1,'message'=>'姓名不能为空']);
        }

        $tel = input('post.telephone');
        if(empty($tel)){
            return  $this->json(['errno'=>-1,'message'=>'手机号不能为空']);
        }

        $idCart = input('post.id_cart');
        if(empty($idCart)){
            return $this->json(['errno'=>-1,'message'=>'身份证号不能为空']);
        }

        $idCartImg1 = input('post.id_cart_img_1');
        if(empty($idCartImg1)){
            return $this->json(['errno'=>-1,'message'=>'身份证号正面不能为空']);
        }

        $idCartImg2 = input('post.id_cart_img_2');
        if(empty($idCartImg2)){
            return $this->json(['errno'=>-1,'message'=>'身份证号反面不能为空']);
        }

        $disabilityCert = input('post.disability_cert');

        $images = input('post.images');

        $data = [
            'id' => $uid,
            'xingming'=>$xingming,
            'telephone'=>$tel,
            'id_cart'=>$idCart,
            'id_cart_img_1'=>$idCartImg1,
            'id_cart_img_2'=>$idCartImg2,
            'disability_cert'=>$disabilityCert,
            'is_vip_apply'=>1
        ];

        Member::update($data);

        MemberImage::where('mid',$uid)->delete();
        foreach ($images as &$image) {
            unset($image['id']);
            $image['mid'] = $uid;
            MemberImage::create($image);
        }

        return $this->json(['errno'=>0,'data'=>$data]);
    }

    function auditDetail(){
        $uid = UID();
        if(empty($uid)){
            return $this->json(['errno'=>-1,'message'=>' 系统异常']);
        }

        $res = Member::field('id,nickname,xingming,is_vip_apply,vip_apply_status,vip_apply_denial_reason,telephone,id_cart,id_cart_img_1,id_cart_img_2,disability_cert')->find($uid);
        if(!empty($res)){
            $res = $res->toArray();
        }

        $res['images'] = MemberImage::where(['mid'=>$uid])->select()->toArray();

        return $this->json(['data'=>$res]);
    }

    function search(){
        $uniacid = uniacid();
        $keyword = input('post.keyword', '', 'serach_in');
        $query = Member::where(['uniacid' => $uniacid]);

        if(!empty($keyword)) {
            $query->where('telephone|nickname', 'like', '%' . $keyword . '%');
        }


        $res = $query->field("id,telephone,nickname")->select()->toArray();

        $data['data'] = $res;
        return $this->json($data);
    }
}
